// 请求页面
import request from './request';
import type {LoginResponse, User, CodeUser, LoginUser} from "@/common/types/userType";
import type {AttributeProduct, Brand, Product, ProductResource} from "@/common/types/goodsType";
import type { ApiResponse, Cart, MyResponse, PageResult } from '@/common/types/apiType'
import type {CategoryTreeResponse} from "@/common/types/category";
import type { DiscountInfo, DiscountQueryParams } from '@/common/types/discountTypes.ts'
import type { userBehaviorType } from '@/common/types/userBehavior.ts'

export function login(user: User) {
  return request.post<{ state: boolean, msg: string, data?: any }>("/user/login", user);
}
export function loginByPhone(user: LoginUser) {
  return request.post<{ state: boolean, msg: string, data?: any }>("/user/loginByPhone", user);
}

export function register(user: CodeUser) {
  return request.post<{ state: boolean, msg: string, data?: any }>("/user/register", user);
}

export function getUserInfo(token: string) {
  return request.get<{ state: boolean, msg: string, data?: User }>("user/info", { headers: { Authorization: `Bearer ${token}` } });
}

export function logout(token: string) {
  return request.post<{ state: boolean, msg: string }>("user/logout", null, { headers: { Authorization: `Bearer ${token}` } });
}

export function sendSms(phone: string) {
  return request.post<{ state: boolean, msg: string }>("user/sendSms", phone);
}
export function updateUser(userId: number, user: Partial<User>) {
  return request.put<{ state: boolean, msg: string }>("user/updateUser", user);
}
export interface ProductPageResponse {
  records: Product[];
  total: number;
}
//商品部分
export async function fetchProductList(page: number, size: number): Promise<ProductPageResponse> {
  const response = await request.get<ProductPageResponse>("/product/list", {
    params: { current: page, size },
  });
  return response.data;
}

export async function getBrandProductsWithConditions(
  params: {
    current?: number;
    size?: number;
    productName?: string;
    productId?: number;
    brandId?:number;
    categoryId?: number;
    minPrice?: number;
    maxPrice?: number;
    updateTime?: string; // 使用 ISO 格式时间字符串
  }
): Promise<ApiResponse<PageResult<Product>>> {
  return request.get('product/list/brand/conditionByUser', { params });
}
export async function recommend(
  params: {
    current?: number;
    size?: number;
  }
): Promise<ApiResponse<PageResult<Product>>> {
  return request.get('product/recommend', { params });
}

// 获取商品属性列表
export async function getAttributes(
  productId: number
): Promise<ApiResponse<any>> {
  return request.get(`attribute/${productId}`);
}
// 获取商品资源列表
export async function getProductResourcesByProductId(
  productId: number
): Promise<ApiResponse<any>> {
  return request.get(`productResource/${productId}`);
}
// 通用商品列表条件查询
export async function getProductListWithConditions(
  params: {
    current?: number;
    size?: number;
    productName?: string;
    minPrice?: number;
    maxPrice?: number;
    categoryId?: number;
  }
): Promise<ApiResponse<PageResult<Product>>> {
  return request.get('product/list/condition', { params });
}
// 获取品牌信息
export async function getBrandInfo(brandId: number): Promise<ApiResponse<Brand>> {
  return request.get(`/api/brand/${brandId}/info`);
}
export async function getCategory():Promise<CategoryTreeResponse>{
  return request.get('/category/tree');
}
// 获取购物车商品列表
export async function getCartItems(page: number, size: number): Promise<ApiResponse<{ records: Cart[]; total: number }>> {
  return request.get(`/cart/list?page=${page}&size=${size}`);
}

// 删除购物车中的商品
export async function deleteCartItem(cartId: number): Promise<ApiResponse<void>> {
  return request.delete(`/cart/delete?cartId=${cartId}`);
}

// 修改购物车中的商品数量或属性
export async function updateCartItem(cart: Cart): Promise<ApiResponse<void>> {
  return request.put('/cart/update', cart);
}
// 添加商品到购物车
export async function addCartItem(cart: {
  attributeId: any;
  quantity: number;
  productId: any;
  brandId: any;
  addPrice: any
}): Promise<ApiResponse<ApiResponse<any>>> {
  return request.post('/cart/add', cart);
}
// 获取地址列表
export const getAddresses = async () => {
  return request.get('/address/list');
};
// 添加地址
export const addNewAddress = async (address: any) => {
  return request.post('address/add', address);
};

// 修改地址
export const updateAddress = async (address: any) => {
  return request.put('address/update', address);
};

// 创建订单
export const createOrder = async (products: Product[],addressId: number) => {
  return request.post(`/order/create?addressId=${addressId}`, products);
};
//收藏商品
export const addToFavorites = async (productId: number) => {
  return request.post(`/favoriteProduct/add?productId=${productId}`);
}
//收藏店铺
export const addToStore = async (brandId: number) => {
  return request.post(`/favoriteBrand/add?brandId=${brandId}`);
}

// 分页查询收藏品牌
export async function getFavoriteBrandList(
  current: number = 1,
  size: number = 10
): Promise<ApiResponse<PageResult<any>>> {
  return request.get('/favoriteBrand/list', {
    params: { current, size }
  });
}
// 添加商品评价
export const addProductReview = async (review: any) => {
  return request.post('/review/add', review);
};
// 删除收藏品牌
export async function deleteFavoriteBrand(favoriteBrandId: number): Promise<ApiResponse<string>> {
  return request.delete(`/favoriteBrand/delete?favoriteBrandId=${favoriteBrandId}`);
}

// 分页查询收藏商品
export async function getFavoriteProductList(
  current: number = 1,
  size: number = 10
): Promise<ApiResponse<PageResult<any>>> {
  return request.get('/favoriteProduct/list', {
    params: { current, size }
  });
}

// 删除收藏商品
export async function deleteFavoriteProduct(favoriteProductId: number): Promise<ApiResponse<string>> {
  console.log(favoriteProductId);
  return request.delete(`/favoriteProduct/delete?favoriteProductId=${favoriteProductId}`);
}
// 按状态查询用户订单
export const getOrdersByStatusForUser = async (status?: number, current = 1, size = 10) => {
  let url = `/order/list/user?current=${current}&size=${size}`;
  if (status) {
    url += `&status=${status}`;
  }
  return request.get(url);
};
// 按状态查询商品评价
export const getProductComment = async (productId:number) => {
  return request.get("review/list?productId=" + productId);
};
// 修改订单信息
export const updateOrder = async (order: any) => {
  return request.put('/order/update', order);
};

// 取消订单
export const cancelOrder = async (order: any, reason: string) => {
  return request.put(`/order/cancel?reason=${reason}`, order);
};

// 用户确认收货
export const confirmReceipt = async (orderId: number) => {
  return request.put(`/order/confirmReceipt?orderId=${orderId}`);
};

// 申请退货
export const refundOrder = async (order: any, reason: string) => {
  return request.put(`/order/refund?reason=${reason}`, order);
};

// 支付接口
export const payApi = async (traceNo: string) => {
  return request.get(`/alipay/pay?traceNo=${traceNo}`);
};
// 用户行为接口 行为类型、品类ID、父级品类ID

export const userBehaviorApi = async (userBehavior:userBehaviorType) => {
  return request.post(`/userBehavior/add`,userBehavior);
};
//优惠券模块
export const DiscountAPI = {
// 分页查询
  getList: (params: DiscountQueryParams) =>
    request.get<MyResponse<PageResult<DiscountInfo>>>('/api/discountInfo/list', { params }),
  getDiscount: (discountId: number) =>
    request.post<MyResponse<PageResult<DiscountInfo>>>(`/discount/claim?discountId=${discountId}`),
  getDiscountClaimsByUserId: (params: DiscountQueryParams) =>
    request.get<MyResponse<PageResult<DiscountInfo>>>(`/discount/list`,{params}),
};
// 获取全部联系人
export const getChatContacts = async () => {
  return request.get('/chat/contacts');
};

// 清空未读数
export const clearUnreadCount = async (targetId: number) => {
  return request.post(`/chat/contacts/clearUnread?targetId=${targetId}`);
};

export const getChatMessages = async (targetId: number, page: number = 1, pageSize: number = 20) => {
  return request.get(`/chat/private/history`, {
    params: {
      receiverId:targetId,
      page,
      pageSize
    }
  });
};
